<?php
//Start user session here?
session_start();


	require('../photo.php');
	
	//Idea: Read the 'json' file to find what photo id we
    //			are on before writing to the file.
	$fp = fopen("../Photos.txt", 'rb');
	if (!$fp) {
        echo "<b> could not open file<p>";
        exit;
    }
	
	$lastID = -1;
	while (!feof($fp)) {
        $temp = fgets($fp, 999);
        if (!$temp)
            break;
		
        $photo = new Photo();
        $photo->fillFromJSON($temp);
        $lastID = (int)$photo->id;
		//echo "$lastID";
    }
	fclose($fp);
	
	//grab the metadata that was saved/passed through the session.
	//list($fileName, $theDate, $theTime, $theLat, $theLong, $view, $theCity) = explode(';',$_SESSION['meta_data']);
	//[0] => fileName, [1] => theDate, [2] => theTime, [3] => theLat, [4] => theLong, [5] => theCity, [6] => view
	$meta_data = explode(';',$_SESSION['meta_data']);
	print_r($meta_data);
	
	//Write the metadata as a data entry to Photos.txt which is a json encoded text file.
	$fp = fopen("../Photos.txt", 'ab');
	if (!$fp) {
        echo "<b> could not open file<p>";
        exit;
    }
	
	$newPhoto = new Photo();
	
	$newPhoto->id = $lastID + 1;
	$newPhoto->user = $_SESSION['valid_user'];
	/*$newPhoto->view = $_POST['view'];
	$newPhoto->fileName = $_POST['fileName'];
	$newPhoto->theDate = $_POST['theDate'];
	$newPhoto->theTime = $_POST['theTime'];
	$newPhoto->theLat = $_POST['theLat'];
	$newPhoto->theLong = $_POST['theLong'];
	$newPhoto->theCity = $_POST['theCity'];*/
	
	$newPhoto->view = $meta_data[6];
	$newPhoto->fileName = $meta_data[0];
	$newPhoto->theDate = $meta_data[1];
	$newPhoto->theTime = $meta_data[2];
	$newPhoto->theLat = $meta_data[3];
	$newPhoto->theLong = $meta_data[4];
	$newPhoto->theCity = $meta_data[5];
	
	$json = json_encode($newPhoto);
	fwrite($fp, $json, strlen($json));
	fwrite($fp, "\n");
	
	fclose($fp);
	
	print_r($newPhoto);
	
	echo '<script>window.location.href = "../liveIndex.php"</script>';
?>

<!-- <a href="../liveIndex.php">Return</a> -->